Units and constants

Despite being conceptually simple, changing units can become a tedious task. Specially when complex algebraic expressions appear. Fortunately, astropy has the units submodule to perform such tasks.

This is allowed by a new class called quantity that inclues both a numerical value and a physical unit.


In [ ]:
from astropy import units as u # This imports the new class 
import numpy as np

In [ ]:
d = 4.0 * u.parsec

In [ ]:
print(d)

In [ ]:
type(d)

This structure can also be initialized with lists and numpy arrays


In [ ]:
d = np.array([3,6,12]) * u.parsec

In [ ]:
print(d)

In [ ]:
d.value # value is one of the attributes of this class

In [ ]:
d.unit # the unit is another attribute

Now we can quickly change the units of this quantity using the method to()


In [ ]:
d.to(u.km)

The real power of the units submodule comes at the moment of computing quantities with mixed units


In [ ]:
x = 4.0 * u.parsec # 4 parsec
t = 6.0 * u.year # 6 years
v = x/t

In [ ]:
print(v)

Let's change the units to $km/s$


In [ ]:
v.to(u.km/u.s)

Physical constants are also available


In [ ]:
from astropy import constants as c

In [ ]:
c.G # The gravitational constant

In [ ]:
c.c # The speed of light

Exercise 1.1

The free fall time is an useful quantity in gravitational studies. It represents the typical time-scale for a system of density $\rho$ evolving under its own gravity.

Its functional form is:

$$ t_{ff} = \sqrt{\frac{1}{G\rho}} $$

Compute the free fall time in units of years for the following cases

  1. The Earth-Moon system.
  2. The Sun-Earth system.
  3. The Milky Way.

In [ ]:

Exercise 1.2

The Alfven velocity (in cgs units) of a plasma with ion number density $n$ and ion mass $m$ in a magnetic field $B$ can be defined as:

$$ v = \frac{B}{\sqrt{4\pi n m}} $$

Estimate the Alfven velocity in $km/s$ for the solar wind assuming that you are close to the Solar corona.


In [ ]: